//加解密
import { encryptMD5 } from "../crypt/index"
//uuid
const { v4: uuidv4 } = require('uuid');

//session请求参数
export const generateSessionParams = () => {
    //session请求参数
    const timestamp = Date.now().toString();//时间戳
    const appVersion = "appVersion";//app版本号
    const channel = "channel";//渠道
    const osVersion = "osVersion";
    const apiLevel = "apiLevel";
    const screenWidth = "screenWidth";
    const screenHeight = "screenHeight";
    const manufacturer = "manufacturer";
    const deviceUniqueId = generateEquipmentId();
    //签名按照顺序全小写再md5
    const signature =
        timestamp.toLowerCase()
        + screenHeight.toLowerCase()
        + appVersion.toLowerCase()
        + osVersion.toLowerCase()
        + deviceUniqueId.toLowerCase()
        + screenWidth.toLowerCase()
        + channel.toLowerCase()
        + manufacturer.toLowerCase()
        + apiLevel.toLowerCase()
        + timestamp.toLowerCase()
    //构建请求参数
    const params = new Map()
    params.set('timestamp', timestamp)
    params.set('appVersion', appVersion)
    params.set('channel', channel)
    params.set('osVersion', osVersion)
    params.set('apiLevel', apiLevel)
    params.set('screenWidth', screenWidth)
    params.set('screenHeight', screenHeight)
    params.set('manufacturer', manufacturer)
    params.set('deviceUniqueId', deviceUniqueId)
    params.set('signature', encryptMD5(signature))
    return params;
}

// 定义所有可能的字符
const CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

/**
 * 生成设备唯一id
 * @return {string} EquipmentId JSON字符串
 */
function generateEquipmentId() {
    //创建新的设备id
    const seed1 = uuidv4(); // uuid
    const seed2 = String(Date.now());
    const seed3 = getSed();
    const seed4 = getSed();
    const seed5 = getSed();

    // 按一定的顺序1-3-1-4-2-5->全部小写再md5
    const s = seed1.toLowerCase() +
        seed3.toLowerCase() +
        seed1.toLowerCase() +
        seed4.toLowerCase() +
        seed2.toLowerCase() +
        seed5.toLowerCase();
    const dynamicSignature = encryptMD5(s);

    const paramsMap = {
        seed1: seed1,
        seed2: seed2,
        seed3: seed3,
        seed4: seed4,
        seed5: seed5,
        signature: dynamicSignature
    };
    const id = JSON.stringify(paramsMap); // map->json字符串
    return id
}

function getSed() {
    let result = '';
    for (let i = 0; i < 4; i++) {
        result += CHARS.charAt(Math.floor(Math.random() * CHARS.length));
    }
    return result;
}